package com.syqc.comlib.custom

import android.animation.ObjectAnimator
import android.app.Activity
import android.content.Context
import android.view.LayoutInflater
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.syqc.comlib.R
import com.syqc.comlib.utils.MLog
import java.lang.ref.WeakReference

/**
 * LoadDialog工具类
 */
object MLoadingPortDialog {

    private var loadingDialog: AlertDialog? = null
    private var reference: WeakReference<Activity?>? = null
    private var rotation: ObjectAnimator? = null

    private fun init(activity: Activity, message: String) {
        if (loadingDialog == null || reference == null || reference!!.get() == null || reference!!.get()!!.isFinishing) {
            reference = WeakReference(activity)
            initDialog(activity, message)
        }
    }

    /**
     * 初始化Dialog
     *
     * @param activity
     */
    private fun initDialog(activity: Context, message: String) {
        val builder =
            AlertDialog.Builder(activity, R.style.ProgressDialog)
        val view =
            LayoutInflater.from(activity).inflate(R.layout.dialog_loading, null)
        builder.setView(view)
        val toastText = view.findViewById<TextView>(R.id.tvProgressMessage)
        val imageView = view.findViewById<ImageView>(R.id.ivLoading)
        toastText.text = message
        rotation = ObjectAnimator.ofFloat(imageView, "rotation", 0f, 360f)
        rotation?.repeatCount = ObjectAnimator.INFINITE
        rotation?.duration = 2000 // 设置动画持续时间（毫秒）
        rotation?.start() // 开始动画
        builder.setCancelable(false)
        loadingDialog = builder.create()
    }


    /**
     * 显示Dialog
     *
     * @param activity 上下文
     * @param massage  显示信息
     */
    fun showLoading(
        activity: Activity,
        massage: String = activity.getString(R.string.desc_loading_port)
    ) {
        if (loadingDialog != null && loadingDialog!!.isShowing) return
        init(activity, massage)
        loadingDialog?.show()
    }

    /**
     * 关闭Dialog
     */
    fun dismiss() {
        loadingDialog?.let {

            if (it.isShowing) it.dismiss()
        }
    }

    /**
     * 是否可以点击空白和返回键退出请求
     *
     * @param cancelable
     */
    fun setCancelable(cancelable: Boolean) {
        loadingDialog?.setCancelable(cancelable)
    }

    /**
     * 清除Dialog
     */
    fun clear() {
        MLog.e("上下文   clear     ")
        dismiss()
        loadingDialog = null
        reference?.clear()
        reference = null
        rotation?.cancel()
        rotation = null
    }
}
